const { Controller } = require('egg');
const WechatPay = require('../../utils/open');
const { formatStatus } = require('../../utils/util');

class WechatPayController extends Controller {
  /**
   *
   * @api {POST} /api/wechatpay 创建微信支付
   * @apiName 创建微信支付
   * @apiGroup wehcatpay
   * @apiVersion  1.0.0
   *
   *
   * @apiParam  {String} out_trade_no 订单号
   *
   * @apiSuccess (200) {type} name description
   *
   * @apiParamExample  {type} Request-Example:
   * {
   *     out_trade_no : 29377590288375
   * }
   *
   *
   * @apiSuccessExample {type} Success-Response:
   * {
   *     property : value
   * }
   *
   *
   */
  async create() {
    const { ctx, service } = this;

    /** 校验参数 */
    const requireAttributes = ['out_trade_no'];
    const { checkDataRes } = new ctx.helper.checkData(this, requireAttributes);
    if (!checkDataRes) return;

    /** 根据订单ID获取订单信息 */
    const { out_trade_no } = ctx.request.body;
    const isOrderExited = await service.shop.order.getOrderById(out_trade_no);

    if (!isOrderExited) {
      ctx.body = ctx.response.error('没有找到该订单的信息哦');
      return;
    }

    const orderInfo = isOrderExited.dataValues;

    const params = {
      description: `订单号：${out_trade_no}`,
      out_trade_no,
      notify_url: 'https://test-shopping-back.bluej.cn/api/wechatpay/notify',
      total: +orderInfo.total_price * 100,
    };

    try {
      const { data } = await WechatPay.createPayment(params);
      ctx.body = ctx.response.success(data.data, data.msg);
    } catch (error) {
      console.log(error);
      ctx.body = ctx.response.error('微信支付创建失败');
    }
  }

  /**
   *
   * @api {GET} /wechatpay 查询微信支付
   * @apiName 查询微信支付
   * @apiGroup wechatpay
   * @apiVersion  1.0.0
   *
   *
   * @apiParam  {String} out_trade_no 订单号
   *
   * @apiSuccess (200) {type} name description
   *
   * @apiParamExample  {type} Request-Example:
   * {
   *     out_trade_no : 29377590288375
   * }
   *
   *
   * @apiSuccessExample {type} Success-Response:
   * {
   *     property : value
   * }
   *
   *
   */
  async get() {
    const { ctx } = this;

    /** 校验参数 */
    const requireAttributes = ['out_trade_no'];
    const { checkDataRes } = new ctx.helper.checkData(this, requireAttributes);
    if (!checkDataRes) return;

    try {
      const { out_trade_no } = ctx.query;
      const { data } = await WechatPay.query(out_trade_no);
      ctx.body = ctx.response.success(data.data, data.msg);
    } catch (error) {
      ctx.body = ctx.response.error({ err: error.message });
    }
  }

  /**
   *
   * @api {DELETE} /wehcatpay 关闭微信支付
   * @apiName 关闭微信支付
   * @apiGroup wechatpay
   * @apiVersion  1.0.0
   *
   *
   * @apiParam  {String} out_trade_no 订单号
   *
   * @apiSuccess (200) {type} name description
   *
   * @apiParamExample  {type} Request-Example:
   * {
   *     out_trade_no : 29377590288375
   * }
   *
   *
   * @apiSuccessExample {type} Success-Response:
   * {
   *     property : value
   * }
   *
   *
   */
  async close() {
    const { ctx } = this;

    /** 校验参数 */
    const requireAttributes = ['out_trade_no'];
    const { checkDataRes } = new ctx.helper.checkData(this, requireAttributes);
    if (!checkDataRes) return;

    try {
      const { out_trade_no } = ctx.query;
      const { data } = await WechatPay.close(out_trade_no);
      ctx.body = ctx.response.success(data.data, data.msg);
    } catch (error) {
      ctx.body = ctx.response.error({ err: error.message });
    }
  }

  /**
   *
   * @api {POST} /wechatpay/refund 退款微信支付
   * @apiName 退款微信支付
   * @apiGroup wechatpay
   * @apiVersion  1.0.0
   *
   *
   * @apiParam  {String} out_trade_no 订单号
   * @apiParam  {String} out_refund_no 退款单号
   * @apiParam  {String} reason 退款原因
   * @apiParam  {Number} refund 退款金额
   * @apiParam  {Number} total 原金额
   *
   * @apiSuccess (200) {type} name description
   *
   * @apiParamExample  {type} Request-Example:
   * {
   *     out_trade_no : 29377590288375,
   *     out_refund_no : 29377590288375,
   *     reason : "不想要了",
   *     refund : 1.0,
   *     total : 1.0
   * }
   *
   *
   * @apiSuccessExample {type} Success-Response:
   * {
   *     property : value
   * }
   *
   *
   */
  async refund() {
    const { ctx, service } = this;
    const { out_trade_no, reason } = ctx.request.body;

    /** 校验参数 */
    const requireAttributes = ['out_trade_no', 'reason'];
    const { checkDataRes } = new ctx.helper.checkData(this, requireAttributes);
    if (!checkDataRes) return;

    const isOrderExited = await service.shop.order.getByOrderId(out_trade_no);
    if (!isOrderExited)
      return (ctx.body = ctx.response.success('该订单不存在'));

    try {
      const order = isOrderExited.dataValues;
      const {
        data: { data },
      } = await WechatPay.refunds({
        out_trade_no,
        out_refund_no: out_trade_no,
        reason,
        total: +order.total_price * 100,
        refund: +order.total_price * 100,
      });

      if (data.status === 'PROCESSING') {
        await service.shop.order.updateByOrderId(out_trade_no, {
          status: '5',
        });
      }

      if (data.status === 'SUCCESS') {
        await service.shop.order.updateByOrderId(out_trade_no, {
          status: '6',
        });
      }

      ctx.body = ctx.response.success(data, data.message);
    } catch (error) {
      ctx.body = ctx.response.error({ err: error.message });
    }
  }

  async notify() {
    const { ctx, service } = this;
    const { out_trade_no, trade_type, trade_state, success_time } =
      ctx.request.body;

    console.log('支付回调数据：', ctx.request.body);
    /** 
     *  
      {
        out_trade_no: '1669021951178',
        trade_type: 'NATIVE',
        trade_state: 'SUCCESS',
        trade_state_desc: '支付成功',
        bank_type: 'OTHERS',
        success_time: '2022-11-21T17:30:35+08:00',
        payer: '',
        amount: '',
        transaction_id: '4200001669202211218544895541'
      }
     */

    /** 更新订单状态 */
    const status = formatStatus(trade_state);

    const result = await service.shop.order.updateByOrderId(out_trade_no, {
      mode_of_payment: trade_type,
      status,
      payment_time: new Date(success_time).getTime(),
    });

    console.log('支付回调解密：', result);

    return ctx.response.success('done');
  }
}

module.exports = WechatPayController;
